package com.jin.webvideo.config.filter.access;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 实现类
 *
 * @author biao532
 * @date 2023/12/04 14:55
 **/
public class GlobalImpl implements GlobalStore {
    private Map<String, Cache<String, Object>> cacheMap = new HashMap<>();
    public static GlobalStore GLOBAL = new GlobalImpl();

    @Override
    public <T> Cache<String, T> getOrCreateExpireCache(String key, long expire) {
        if (cacheMap.containsKey(key)) {
            return (Cache<String, T>) cacheMap.get(key);
        }
        Cache<String, Object> cache = CacheBuilder.newBuilder().expireAfterAccess(expire, TimeUnit.MILLISECONDS)
                .softValues().build();
        cacheMap.put(key, cache);
        return (Cache<String, T>) cache;
    }

    @Override
    public <T> Cache<String, T> get(String key) {
        return (Cache<String, T>) cacheMap.get(key);
    }

    @Override
    public void remove(String key) {
        cacheMap.remove(key);
    }
}
